package com.dr.java.net.server;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URLConnection;

/**
 * Created by rui on 2018/4/24.
 */
public class MyTomcat {

    public static void main(String[] args) {

        ServerSocket server = null;
        Socket socket = null;
        try {
            server = new ServerSocket(8080);

            socket = server.accept();

            int len;
            byte[] buf = new byte[socket.getInputStream().available()];

            BufferedInputStream reader = new BufferedInputStream(socket.getInputStream());

            reader.read(buf);
            System.out.println(new String(buf));

            PrintWriter printer = new PrintWriter(socket.getOutputStream(), true);

            String string="<h1>hello</h1>";
            printer.println("HTTP/1.0 200 OK");// 必填！！！返回应答消息,并结束应答
            printer.println("Content-Type:text/html");//不填将不会渲染
            printer.println();// 根据 HTTP 协议, 空行将结束头信息
            printer.println(string);
            printer.println(string);
            printer.println(string);
            printer.println(string);
            printer.flush();
            printer.close();
            socket.close();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (server != null) {
                try {
                    server.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
